<template>
  <div class="channel-management">
    <!-- 新增菜单 -->
     <el-menu
        default-active="2"
        class="el-menu-vertical-demo custom-menu"
        @open="handleOpen"
        @close="handleClose"
      >
        <el-sub-menu index="site-menu">
          <template #title>
            <el-icon><location /></el-icon>
            <span>站点选择</span>
          </template>
            <el-menu-item v-for="site in sites" :key="site.id" index="'site-item-' + site.id" @click="selectedSiteId=site.id;handleSiteChange()">{{ site.name }}</el-menu-item>
        </el-sub-menu>
        <el-sub-menu index="1">
          <template #title>
            <el-icon><location /></el-icon>
            <span>栏目选择</span>
          </template>
            <el-menu-item index="1-1">item one</el-menu-item>
            <el-menu-item index="1-2">item two</el-menu-item>
            <el-menu-item index="1-3">item three</el-menu-item>
            <el-menu-item index="1-4">item one</el-menu-item>
        </el-sub-menu>
      </el-menu>
    <!-- 右边栏 -->
     <div class="content">
      <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">栏目管理</h1>
        <p class="page-desc">管理站点栏目结构，支持多级栏目和不同类型配置</p>
      </div>
      <div class="header-right">
        <div class="site-selector">
          <span class="site-label">站点：</span>
          <el-select
            v-model="selectedSiteId"
            placeholder="选择站点"
            @change="handleSiteChange"
            class="site-select"
          >
            <el-option
              v-for="site in sites"
              :key="site.id"
              :label="site.name"
              :value="site.id"
            />
          </el-select>
        </div>
        <el-dropdown @command="handleColumnCommand">
          <el-button size="large" class="column-btn">
            <el-icon><Setting /></el-icon>
            字段配置
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="column in availableColumns"
                :key="column.key"
                :command="column.key"
              >
                <el-checkbox
                  :model-value="visibleColumns.includes(column.key)"
                  @change="toggleColumn(column.key)"
                >
                  {{ column.label }}
                </el-checkbox>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button type="primary" size="large" @click="handleAdd" class="add-btn">
          <el-icon><Plus /></el-icon>
          新建栏目
        </el-button>
      </div>
    </div>

    <!-- 栏目表格 -->
    <div class="channel-container" v-loading="loading">
      <!-- 调试信息 -->
      <div v-if="channelTree.length > 0" class="debug-info">
        共找到 {{ channelTree.length }} 个栏目
      </div>

      <!-- 栏目表格 -->
      <div class="channel-table">
        <el-table
          ref="tableRef"
          :data="flatChannelList"
          row-key="id"
          stripe
          style="width: 100%"
          :header-cell-style="{ background: '#f8f9fa', color: '#606266' }"
        >
          <el-table-column v-if="visibleColumns.includes('name')" prop="name" label="栏目名称" min-width="300">
            <template #default="{ row }">
              <div
                class="channel-name-wrapper"
                :class="{ 'is-parent': !row.parentId || row.parentId === 0 }"
                :style="{ '--depth': row.depth || 0 }"
              >
                <!-- 层级连接线 -->
                <div class="tree-lines" v-if="row.depth > 0">
                  <div
                    v-for="i in row.depth"
                    :key="i"
                    class="tree-line"
                    :class="{ 'is-last': i === row.depth }"
                  ></div>
                </div>

                <div class="channel-content">
                  <!-- 层级图标 -->
                  <div class="level-indicator" v-if="row.depth > 0">
                    <div class="connector"></div>
                  </div>

                  <el-icon class="channel-icon">
                    <Folder v-if="!row.parentId || row.parentId === 0" />
                    <FolderOpened v-else />
                  </el-icon>

                  <span class="name-text">{{ row.name }}</span>

                  <el-tag v-if="row.alias" class="alias-tag" size="small" type="info">
                    {{ row.alias }}
                  </el-tag>

                  <!-- 层级标识 -->
                  <span class="level-badge" v-if="!row.parentId || row.parentId === 0">
                    一级栏目
                  </span>
                  <span class="level-badge level-2" v-else-if="row.depth === 1">
                    二级栏目
                  </span>
                  <span class="level-badge level-3" v-else-if="row.depth === 2">
                    三级栏目
                  </span>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column v-if="visibleColumns.includes('type')" prop="type" label="栏目类型" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getTypeTagType(row.type)" size="small">
                {{ getTypeText(row.type) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column v-if="visibleColumns.includes('channelTemplate')" prop="channelTemplate" label="栏目模板" width="200" align="center">
            <template #default="{ row }">
              <span class="template-text">{{ row.channelTemplate || '默认' }}</span>
            </template>
          </el-table-column>

          <el-table-column v-if="visibleColumns.includes('nav')" prop="nav" label="导航显示" width="150" align="center">
            <template #default="{ row }">
              <el-tag :type="row.nav ? 'success' : 'info'" size="small">
                {{ row.nav ? '显示' : '隐藏' }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column v-if="visibleColumns.includes('status')" prop="status" label="状态" width="120" align="center">
            <template #default="{ row }">
              <el-switch
                v-model="row.status"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(row)"
                size="small"
              />
            </template>
          </el-table-column>

          <el-table-column v-if="visibleColumns.includes('orderNum')" prop="orderNum" label="排序" width="120" align="center" />

          <el-table-column label="操作" width="240" align="center" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button
                  type="primary"
                  size="small"
                  @click="handleEdit(row)"
                  :icon="Edit"
                >
                  编辑
                </el-button>
                <el-button
                  type="success"
                  size="small"
                  @click="handleAddChild(row)"
                  :icon="Plus"
                >
                  子栏目
                </el-button>
                <el-button
                  type="info"
                  size="small"
                  @click="viewArticles(row)"
                  :icon="Document"
                >
                  文章
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="handleDelete(row)"
                  :icon="Delete"
                >
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && channelTree.length === 0" class="empty-state">
        <el-empty description="暂无栏目数据">
          <el-button type="primary" @click="handleAdd">创建第一个栏目</el-button>
        </el-empty>
      </div>
    </div>
    
    <!-- 栏目表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="栏目名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入栏目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="栏目别名" prop="alias">
              <el-input v-model="form.alias" placeholder="请输入栏目别名" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="栏目类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择栏目类型">
                <el-option label="常规栏目" :value="1" />
                <el-option label="单页栏目" :value="2" />
                <el-option label="外部链接" :value="3" />
                <el-option label="链接到子栏目" :value="4" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上级栏目" prop="parentId" v-if="!isEdit">
              <el-tree-select
                v-model="form.parentId"
                :data="channelTreeOptions"
                :props="{ label: 'name', value: 'id' }"
                placeholder="请选择上级栏目"
                check-strictly
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="栏目图片" prop="image" v-if="form.type !== 3">
          <div class="image-upload-wrapper">
            <el-upload
              class="image-uploader"
              action="/cms/admin/attachment/upload"
              :show-file-list="false"
              :on-success="handleImageSuccess"
              :before-upload="beforeImageUpload"
              accept="image/*"
            >
              <img v-if="form.image" :src="getImageUrl(form.image)" class="uploaded-image" />
              <div v-else class="upload-placeholder">
                <el-icon class="upload-icon"><Plus /></el-icon>
                <div class="upload-text">点击上传图片</div>
                <div class="upload-tip">支持 JPG、PNG、GIF、WebP 格式，最大 {{ FILE_SIZE_LIMITS.IMAGE }}MB</div>
              </div>
            </el-upload>
            <el-button v-if="form.image" size="small" type="danger" @click="removeImage" style="margin-top: 8px;">
              删除图片
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item label="链接地址" prop="linkUrl" v-if="form.type === 3">
          <el-input v-model="form.linkUrl" placeholder="请输入链接地址" />
        </el-form-item>
        <el-row :gutter="20" v-if="form.type === 1">
          <el-col :span="12"> 
            <el-form-item label="栏目数据模型" prop="channelModelId"> 
              <el-select v-model="form.channelModelId" placeholder="请选择栏目的数据模型" clearable> 
                <el-option
                  v-for="option in modelOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                /> 
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="栏目模板" prop="channelTemplate">
              <el-select v-model="form.channelTemplate" placeholder="请选择栏目模板" clearable>
                <el-option
                  v-for="option in templateOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="form.type === 1">
          <el-col :span="12"> 
            <el-form-item label="文章数据模型" prop="channelModelId"> 
              <el-select v-model="form.channelModelId" placeholder="请选择文章的数据模型" clearable> 
                <el-option
                  v-for="option in modelOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                /> 
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文章模板" prop="articleTemplate">
              <el-select v-model="form.articleTemplate" placeholder="请选择文章模板" clearable>
                <el-option
                  v-for="option in articleTemplateOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="每页数量" prop="pageSize">
              <el-input-number v-model="form.pageSize" :min="1" :max="100" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="新窗口打开" prop="targetBlank" v-if="form.type === 3">
              <el-switch v-model="form.targetBlank" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="SEO关键词" prop="keywords">
          <el-input
            v-model="form.keywords"
            type="textarea"
            :rows="2"
            placeholder="请输入SEO关键词，多个关键词用逗号分隔"
          />
        </el-form-item>
        
        <el-form-item label="SEO描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入SEO描述"
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="导航显示" prop="nav">
              <el-radio-group v-model="form.nav">
                <el-radio :label="1">显示</el-radio>
                <el-radio :label="0">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
     </div>
  </div>
</template>

<script setup lang="ts">
import { FILE_SIZE_LIMITS, validateImageFile } from '@/config/upload'
import { Delete, Document, Edit, Folder, FolderOpened, Plus, Setting } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
// import { channelApi } from '@/api/channel'
// import { siteApi } from '@/api/site'
// import type { Channel, Site } from '@/types/api'

// 临时类型定义
interface Channel {
  id: string | number
  siteId: string | number
  parentId: string | number
  name: string
  alias?: string
  type: number
  channelModelId?: string | number
  articleModelId?: string | number
  channelTemplate?: string
  articleTemplate?: string
  pageSize?: number
  keywords?: string
  description?: string
  depth?: number
  orderNum: number
  status: number
  nav: number
  children?: Channel[]
  hasChildren?: boolean
  image?: string
  linkUrl?: string
  targetBlank?: number
}

interface Site {
  id: string | number
  name: string
}

const router = useRouter()
const loading = ref(false)
const dialogVisible = ref(false)
const submitting = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()

// 选中的站点ID
const selectedSiteId = ref<string | number>()

// 站点列表
const sites = ref<Site[]>([])

// 栏目树数据
const channelTree = ref<Channel[]>([])

// 字段配置
const availableColumns = ref([
  { key: 'name', label: '栏目名称' },
  { key: 'type', label: '栏目类型' },
  { key: 'channelTemplate', label: '栏目模板' },
  { key: 'nav', label: '导航显示' },
  { key: 'status', label: '状态' },
  { key: 'orderNum', label: '排序' }
])

const visibleColumns = ref(['name', 'type', 'channelTemplate', 'nav', 'status', 'orderNum'])

// 处理栏目树数据，确保有 hasChildren 属性
const processChannelTree = (channels: Channel[]): Channel[] => {
  return channels.map(channel => ({
    ...channel,
    hasChildren: channel.children && channel.children.length > 0,
    children: channel.children ? processChannelTree(channel.children) : undefined
  }))
}

// 模板选项
const templateOptions = ref([
  { label: '默认模板', value: 'default' },
  { label: '列表模板', value: 'list' },
  { label: '图片列表', value: 'image-list' },
  { label: '新闻列表', value: 'news-list' },
  { label: '产品列表', value: 'product-list' },
  { label: '单页模板', value: 'page' },
  { label: '关于我们', value: 'about' },
  { label: '联系我们', value: 'contact' }
])

const articleTemplateOptions = ref([
  { label: '默认文章', value: 'default' },
  { label: '新闻详情', value: 'news-detail' },
  { label: '产品详情', value: 'product-detail' },
  { label: '图文详情', value: 'image-detail' }
])

// 表单数据
const form = ref<Partial<Channel>>({
  name: '',
  alias: '',
  type: 1,
  siteId: undefined,
  parentId: 0,
  channelTemplate: '',
  articleTemplate: '',
  image: '',
  linkUrl: '',
  targetBlank: 0,
  pageSize: 20,
  keywords: '',
  description: '',
  orderNum: 999999,
  status: 1,
  nav: 1,

})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入栏目名称', trigger: 'blur' },
    { min: 1, max: 100, message: '栏目名称长度在 1 到 100 个字符', trigger: 'blur' },
  ],
  alias: [
    { max: 50, message: '栏目别名长度不能超过 50 个字符', trigger: 'blur' },
  ],
  type: [
    { required: true, message: '请选择栏目类型', trigger: 'change' },
  ],
  linkUrl: [
    { required: true, message: '请输入链接地址', trigger: 'blur' },
  ],
  keywords: [
    { max: 500, message: 'SEO关键词长度不能超过 500 个字符', trigger: 'blur' },
  ],
  description: [
    { max: 1000, message: 'SEO描述长度不能超过 1000 个字符', trigger: 'blur' },
  ],
}

// 对话框标题
const dialogTitle = computed(() => isEdit.value ? '编辑栏目' : '新建栏目')

// 扁平化栏目列表（用于表格显示）
const flatChannelList = computed(() => {
  const flattenChannels = (channels: Channel[], depth = 0): Channel[] => {
    const result: Channel[] = []
    for (const channel of channels) {
      // 创建一个新的栏目对象，不包含children属性，避免重复显示
      const flatChannel = {
        ...channel,
        depth,
        children: undefined // 移除children属性，避免重复
      }
      result.push(flatChannel)

      // 递归添加子栏目
      if (channel.children && channel.children.length > 0) {
        result.push(...flattenChannels(channel.children, depth + 1))
      }
    }
    return result
  }
  return flattenChannels(channelTree.value)
})

// 栏目树选项（用于选择上级栏目）
const channelTreeOptions = computed(() => {
  const options = [{ id: 0, name: '顶级栏目', children: [] as Channel[] }]
  options[0].children = channelTree.value
  return options
})

// 获取站点列表
const getSites = async () => {
  try {
    console.log('正在获取站点列表...')

    // 从真实数据库获取站点数据
    const response = await fetch('/cms/admin/site/tree', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        // 如果需要认证，添加token
        // 'Authorization': `Bearer ${token}`
      }
    })

    if (response.ok) {
      const data = await response.json()
      console.log('站点列表响应:', data)

      if (data.code === 0 && data.data) {
        sites.value = data.data

        if (sites.value.length > 0 && !selectedSiteId.value) {
          selectedSiteId.value = sites.value[0].id // 保持原始格式，避免精度丢失
          console.log('自动选择站点ID:', selectedSiteId.value)
          getChannelTree()
        }
      } else {
        console.warn('获取站点数据失败:', data.message)
        sites.value = []
      }
    } else {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
  } catch (error) {
    console.error('获取站点列表失败:', error)
    ElMessage.error('获取站点列表失败，请检查网络连接')

    // 清空站点列表，不使用模拟数据
    sites.value = []
    selectedSiteId.value = undefined
  }
}

// 获取栏目树
const getChannelTree = async () => {
  if (!selectedSiteId.value) return

  try {
    loading.value = true
    console.log('正在获取栏目树，站点ID:', selectedSiteId.value)

    // 从真实数据库获取栏目数据
    const response = await fetch(`/cms/admin/channel/tree?siteId=${selectedSiteId.value}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        // 如果需要认证，添加token
        // 'Authorization': `Bearer ${token}`
      }
    })

    if (response.ok) {
      const data = await response.json()
      console.log('栏目树响应:', data)

      if (data.code === 0) {
        const rawData = data.data || []
        channelTree.value = processChannelTree(rawData)
        console.log('设置后的栏目树:', channelTree.value)
      } else {
        console.warn('获取栏目数据失败:', data.message)
        channelTree.value = []
        ElMessage.warning(data.message || '获取栏目数据失败')
      }
    } else {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }

  } catch (error) {
    console.error('获取栏目树失败:', error)
    ElMessage.error('获取栏目树失败，请检查网络连接')
    channelTree.value = []
  } finally {
    loading.value = false
  }
}

// 处理站点变更
const handleSiteChange = () => {
  getChannelTree()
}

// 表格引用
const tableRef = ref()

// 字段配置方法
const toggleColumn = (columnKey: string) => {
  const index = visibleColumns.value.indexOf(columnKey)
  if (index > -1) {
    visibleColumns.value.splice(index, 1)
  } else {
    visibleColumns.value.push(columnKey)
  }
}

const handleColumnCommand = (_command: string) => {
  // 这里可以处理其他命令，目前主要通过checkbox处理
}

// 处理新增
const handleAdd = () => {
  if (!selectedSiteId.value) {
    ElMessage.warning('请先选择站点')
    return
  }
  isEdit.value = false
  form.value.siteId = selectedSiteId.value
  dialogVisible.value = true
}

// 处理添加子栏目
const handleAddChild = (row: Channel) => {
  isEdit.value = false
  form.value.siteId = row.siteId
  form.value.parentId = row.id
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row: Channel) => {
  isEdit.value = true
  form.value = { ...row }
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (row: Channel) => {
  ElMessageBox.confirm(`确定要删除栏目"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      // 调用真实的删除API
      const response = await fetch(`/cms/admin/channel/${row.id}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
          // 如果需要认证，添加token
          // 'Authorization': `Bearer ${token}`
        }
      })

      if (response.ok) {
        const data = await response.json()
        if (data.code === 0) {
          ElMessage.success('删除成功')
          getChannelTree()
        } else {
          ElMessage.error(data.message || '删除失败')
        }
      } else {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }
    } catch (error) {
      console.error('删除栏目失败:', error)
      ElMessage.error('删除失败，请检查网络连接')
    }
  })
}

// 处理状态变更
const handleStatusChange = async (row: Channel) => {
  try {
    // 调用真实的状态更新API
    const response = await fetch(`/cms/admin/channel/${row.id}/status`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        // 如果需要认证，添加token
        // 'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({
        status: row.status
      })
    })

    if (response.ok) {
      const data = await response.json()
      if (data.code === 0) {
        ElMessage.success('状态更新成功')
      } else {
        ElMessage.error(data.message || '状态更新失败')
        // 恢复原状态
        row.status = row.status === 1 ? 0 : 1
      }
    } else {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('状态更新失败，请检查网络连接')
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
  }
}

// 查看文章
const viewArticles = (row: Channel) => {
  router.push({
    path: '/content/article',
    query: { channelId: row.id }
  })
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (isEdit.value) {
      // 调用真实的更新API
      const response = await fetch(`/cms/admin/channel/${form.value.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          // 如果需要认证，添加token
          // 'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(form.value)
      })

      if (response.ok) {
        const data = await response.json()
        if (data.code === 0) {
          ElMessage.success('更新成功')
        } else {
          ElMessage.error(data.message || '更新失败')
          return
        }
      } else {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }
    } else {
      // 调用真实的创建API
      const response = await fetch('/cms/admin/channel', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          // 如果需要认证，添加token
          // 'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(form.value)
      })

      if (response.ok) {
        const data = await response.json()
        if (data.code === 0) {
          ElMessage.success('创建成功')
        } else {
          ElMessage.error(data.message || '创建失败')
          return
        }
      } else {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }
    }
    
    dialogVisible.value = false
    getChannelTree()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  form.value = {
    name: '',
    alias: '',
    type: 1,
    siteId: selectedSiteId.value,
    parentId: 0,
    channelTemplate: '',
    articleTemplate: '',
    image: '',
    linkUrl: '',
    targetBlank: 0,
    pageSize: 20,
    keywords: '',
    description: '',
    orderNum: 999999,
    status: 1,
    nav: 1,
  }
  formRef.value?.resetFields()
}



// 获取类型标签类型
const getTypeTagType = (type: number) => {
  const typeMap: Record<number, string> = {
    1: 'primary',
    2: 'success',
    3: 'warning',
    4: 'info',
  }
  return typeMap[type] || 'info'
}

// 图片处理方法
const getImageUrl = (url: string) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  return `/cms${url}`
}

const handleImageSuccess = (response: any) => {
  if (response.code === 0) {
    form.value.image = response.data.url
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.msg || '图片上传失败')
  }
}

const beforeImageUpload = (file: File) => {
  // 使用统一的图片验证
  const validation = validateImageFile(file)
  if (!validation.valid) {
    ElMessage.error(validation.error!)
    return false
  }
  return true
}

const removeImage = () => {
  form.value.image = ''
  ElMessage.success('图片已删除')
}

// 获取类型文本
const getTypeText = (type: number) => {
  const typeMap: Record<number, string> = {
    1: '常规',
    2: '单页',
    3: '链接',
    4: '子栏目',
  }
  return typeMap[type] || '未知'
}

onMounted(() => {
  getSites()
})
</script>

<style scoped lang="scss">
// 二级菜单样式
.custom-menu{
  float: left;
  // display: inline-block;
  width: 15%;
}
.content{
  float: right;
  width: 83%;
}
// 图片上传样式
.image-upload-wrapper {
  .image-uploader {
    border: 2px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;
    width: 200px;
    height: 150px;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      border-color: #409eff;
    }

    .uploaded-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .upload-placeholder {
      text-align: center;
      color: #8c939d;

      .upload-icon {
        font-size: 28px;
        color: #8c939d;
        margin-bottom: 8px;
      }

      .upload-text {
        font-size: 14px;
        margin-bottom: 4px;
      }

      .upload-tip {
        font-size: 12px;
        color: #999;
      }
    }
  }
}

// 确保页面占满整个屏幕
:deep(.el-main) {
  width: 100% !important;
  max-width: none !important;
  padding: 0 !important;
}

.channel-management {
  // padding: 24px;
  background: #f8f9fa;
  min-height: 100vh;
  width: 100%;
  max-width: none;
  box-sizing: border-box;

  .page-header {
  // margin-top: 50px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    width: 100%;

    .header-left {
      .page-title {
        font-size: 20px;
        font-weight: 600;
        color: #303133;
        margin: 0 0 6px 0;
      }

      .page-desc {
        font-size: 13px;
        color: #909399;
        margin: 0;
      }
    }

    .header-right {
      display: flex;
      align-items: center;
      gap: 12px;

      .site-selector {
        display: flex;
        align-items: center;
        gap: 8px;

        .site-label {
          font-size: 14px;
          color: #606266;
          font-weight: 500;
          white-space: nowrap;
        }

        .site-select {
          width: 180px;
        }
      }

      .add-btn {
        height: 36px;
        padding: 0 16px;
        font-size: 13px;
        font-weight: 500;
        border-radius: 4px;
      }
    }
  }

  .channel-container {
    width: 100%;

    .debug-info {
      background: white;
      padding: 10px 16px;
      border-radius: 4px;
      margin-bottom: 16px;
      font-size: 12px;
      color: #909399;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    }

    .channel-table {
      background: white;
      border-radius: 8px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      overflow: hidden;
      width: 100%;

      .channel-name-wrapper {
        display: flex;
        align-items: center;
        width: 100%;
        position: relative;
        padding: 8px 0;

        &.is-parent {
          background: linear-gradient(90deg, rgba(64, 158, 255, 0.05) 0%, transparent 100%);
          border-left: 3px solid #409eff;
          padding-left: 8px;
          margin-left: -8px;
          border-radius: 0 4px 4px 0;
        }

        .tree-lines {
          display: flex;
          position: absolute;
          left: 0;
          top: 0;
          bottom: 0;

          .tree-line {
            width: 20px;
            position: relative;

            &:before {
              content: '';
              position: absolute;
              left: 10px;
              top: 0;
              bottom: 0;
              width: 1px;
              background: #e4e7ed;
            }

            &.is-last:before {
              height: 50%;
            }

            &.is-last:after {
              content: '';
              position: absolute;
              left: 10px;
              top: 50%;
              width: 10px;
              height: 1px;
              background: #e4e7ed;
            }
          }
        }

        .channel-content {
          display: flex;
          align-items: center;
          gap: 8px;
          flex: 1;
          margin-left: calc(var(--depth, 0) * 20px);

          .level-indicator {
            width: 16px;
            height: 16px;
            position: relative;
            flex-shrink: 0;

            .connector {
              position: absolute;
              top: 50%;
              left: 0;
              width: 12px;
              height: 1px;
              background: #c0c4cc;

              &:before {
                content: '';
                position: absolute;
                right: 0;
                top: -2px;
                width: 5px;
                height: 5px;
                border-radius: 50%;
                background: #c0c4cc;
              }
            }
          }

          .channel-icon {
            color: #409eff;
            font-size: 16px;
            flex-shrink: 0;

            .is-parent & {
              color: #67c23a;
              font-size: 18px;
            }
          }

          .name-text {
            font-weight: 500;
            color: #303133;
            font-size: 14px;

            .is-parent & {
              font-weight: 600;
              font-size: 15px;
              color: #409eff;
            }
          }

          .alias-tag {
            font-size: 11px;
            height: 20px;
            line-height: 18px;
            border-radius: 10px;
            padding: 0 8px;
          }

          .level-badge {
            background: linear-gradient(135deg, #409eff, #67c23a);
            color: white;
            font-size: 10px;
            padding: 2px 6px;
            border-radius: 8px;
            font-weight: 500;
            margin-left: 8px;

            &.level-2 {
              background: linear-gradient(135deg, #e6a23c, #f56c6c);
            }

            &.level-3 {
              background: linear-gradient(135deg, #909399, #606266);
            }
          }
        }
      }

      .template-text {
        color: #606266;
        font-size: 13px;
      }

      .action-buttons {
        display: flex;
        gap: 4px;
        justify-content: center;

        .el-button {
          font-size: 12px;
          padding: 4px 8px;
        }
      }

      :deep(.el-table) {
        .el-table__header-wrapper {
          .el-table__header {
            th {
              background: #f8f9fa !important;
              color: #606266 !important;
              font-weight: 600;
              border-bottom: 1px solid #ebeef5;
            }
          }
        }

        .el-table__body-wrapper {
          .el-table__body {
            tr {
              &:hover {
                background: #f5f7fa !important;
              }

              td {
                border-bottom: 1px solid #f0f2f5;
                padding: 12px 0;
              }

              // 子栏目行样式
              &.channel-row-level-1 {
                background: #fafbfc;

                .channel-content {
                  padding-left: 20px;

                  .channel-icon {
                    color: #74b9ff !important;
                    font-size: 14px !important;
                  }

                  .name-text {
                    color: #606266 !important;
                    font-weight: 400 !important;
                    font-size: 14px !important;
                  }
                }
              }

              // 更深层级的子栏目
              &.channel-row-level-2 {
                background: #f5f7fa;

                .channel-content {
                  padding-left: 40px;

                  .channel-icon {
                    color: #a0cfff !important;
                    font-size: 13px !important;
                  }

                  .name-text {
                    color: #909399 !important;
                    font-weight: 400 !important;
                    font-size: 13px !important;
                  }
                }
              }

              // 三级及以上子栏目
              &.channel-row-level-3 {
                background: #f0f2f5;

                .channel-content {
                  padding-left: 60px;

                  .channel-icon {
                    color: #c0c4cc !important;
                    font-size: 12px !important;
                  }

                  .name-text {
                    color: #c0c4cc !important;
                    font-weight: 400 !important;
                    font-size: 12px !important;
                  }
                }
              }
            }
          }
        }

        // 树形表格展开图标样式
        .el-table__expand-icon {
          color: #409eff !important;
          font-size: 12px !important;
          margin-right: 4px !important;
          vertical-align: middle !important;

          &.el-table__expand-icon--expanded {
            transform: rotate(90deg);
          }
        }

        // 确保展开图标和内容在同一行
        .el-table__cell {
          .cell {
            display: flex !important;
            align-items: center !important;
            line-height: 1.5 !important;
          }
        }

        // 树形表格缩进调整
        .el-table__indent {
          width: 16px !important;
        }

        .el-table__placeholder {
          display: none;
        }
      }
    }

    .empty-state {
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 300px;
      background: white;
      border-radius: 8px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .channel-management {
    padding: 16px;

    .page-header {
      flex-direction: column;
      align-items: stretch;
      gap: 12px;
      padding: 16px;

      .header-right {
        flex-direction: column;
        gap: 8px;

        .site-select {
          width: 100%;
        }

        .add-btn {
          width: 100%;
          justify-content: center;
        }
      }
    }

    .channel-container {
      .channel-table {
        :deep(.el-table) {
          .action-buttons {
            flex-direction: column;
            gap: 2px;

            .el-button {
              width: 100%;
              margin: 0;
            }
          }
        }
      }
    }

    // 操作按钮样式
    .action-buttons {
      display: flex;
      gap: 8px;
      justify-content: center;
      flex-wrap: wrap;

      .el-button {
        border-radius: 4px;
        font-size: 12px;
        padding: 4px 8px;
        transition: all 0.2s ease;

        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
      }
    }
  }
}

// 栏目层级缩进样式
.indent-space {
  display: inline-block;
  width: 20px;
  height: 1px;
}

.channel-name-wrapper {
  .channel-content {
    display: flex;
    align-items: center;
    gap: 8px;

    .channel-icon {
      color: #409eff;
      font-size: 16px;
    }

    .name-text {
      font-weight: 500;
      color: #303133;
    }

    .alias-text {
      color: #909399;
      font-size: 12px;
      background: #f0f2f5;
      padding: 2px 6px;
      border-radius: 4px;
      margin-left: 8px;
    }
  }
}
</style>
